package lagou.homework.lagouhomework.Unit4.code.q3;

import java.io.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Copy {
    public static void copyFile(String oldPath, String newPath) {
        // 使用缓冲流进行文件拷贝
        BufferedInputStream in = null;
        BufferedOutputStream out = null;

        try {
            // 被拷贝文件
            in = new BufferedInputStream(new FileInputStream(oldPath));
            // 拷贝的文件
            out = new BufferedOutputStream(new FileOutputStream(newPath));
            byte[] arr = new byte[8 * 1024];
            int res = 0;
            // 拷贝
            while ((res = in.read(arr)) != -1) {
                out.write(arr, 0, res);
                System.out.println("拷贝文件完成");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


    public static void copyFolders(String oldPath, String newPath) {

        // 被拷贝的目录位置
        File oldFolder = new File(oldPath);
        // 拷贝到的位置
        File newFolder = new File(newPath);

        // 如果被拷贝的目录不存在，则返回
        if (!oldFolder.exists()) {
            System.out.println("复制的文件夹不存在");
            return;
        }

        // 如果拷贝的目录不存在，则创建目录
        if (!newFolder.exists()) {
            newFolder.mkdirs();
            System.out.println(newPath+ "复制成功");
        }

        // 创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        // 遍历被拷贝的目录
        for (File f : oldFolder.listFiles()) {
            // 向线程池提交任务
            executorService.submit(() -> {
                if (f.isFile()) {
                    // 复制文件
                    Copy.copyFile(f.getAbsolutePath(), newFolder.getAbsolutePath() + "/" + f.getName());
                    System.out.println(f.getName() + "复制成功");
                } else {
                    // 如果是目录，则进行递归
                    Copy.copyFolders(f.getAbsolutePath(), newFolder.getAbsolutePath() + "/" + f.getName());
                }
                return null;
            });
        }
        // 关闭线程池
        executorService.shutdown();

    }
}

